package com.jerry.mingxing.ui.detail;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jerry.mingxing.R;
import com.jerry.mingxing.app.MyApplication;
import com.jerry.mingxing.bean.DetailBean;
import com.jerry.mingxing.config.UrlConfig;
import com.jerry.mingxing.ui.commodity.CommodityActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class DetailActivity extends AppCompatActivity {
    private ListView detail_lv;
    private DetailAdapter detailAdapter;
    private List<DetailBean.DataBean.ItemsBean> totallist=new ArrayList<>();
    private Activity activity=this;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        id = getIntent().getStringExtra("id");
        initView();
        reloaData();
        setListener();
    }

    private void setListener() {
        detail_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(activity, CommodityActivity.class);

                startActivity(intent);
            }
        });
    }

    private void initView() {
        detail_lv= (ListView) findViewById(R.id.detail_lv);
        detailAdapter=new DetailAdapter(totallist,activity);
        detail_lv.setAdapter(detailAdapter);
    }

    private void reloaData() {
        Request request =new Request.Builder().url(UrlConfig.DETAIL+id).build();
        MyApplication.ok.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson=new Gson();
                final DetailBean bean = gson.fromJson(json, new TypeToken<DetailBean>() {
                }.getType());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailAdapter.reloadData(bean.getData().getItems());
                    }
                });
            }
        });
    }
}
